package com.tea.dao;

import com.tea.entity.Order;
import com.tea.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {
    // 添加订单
    public long addOrder(Order order) throws Exception {
        String sql = "INSERT INTO `order` (user_id, total_amount, order_date, status,order_id) VALUES (?,?, ?, ?, ?)";
        Connection conn = DBUtil.getConnection();
            conn.setAutoCommit(true);
        PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        
        ps.setLong(1, order.getUserId());
        ps.setDouble(2, order.getTotalAmount());
        ps.setTimestamp(3, order.getOrderDate());
        ps.setInt(4, order.getStatus());
        ps.setLong(5,order.getOrderId());

        ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        if (rs.next()) {
            return rs.getLong(1);
        }
        return -1;
    }

    // 添加订单（带事务支持）
    public long addOrder(Order order, Connection conn) throws Exception {
        String sql = "INSERT INTO `order` (user_id, total_amount, order_date, status, order_id) VALUES (?, ?, ?, ?, ?)";
        PreparedStatement ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
        
        ps.setLong(1, order.getUserId());
        ps.setDouble(2, order.getTotalAmount());
        ps.setTimestamp(3, order.getOrderDate());
        ps.setInt(4, order.getStatus());
        ps.setLong(5, order.getOrderId());

        ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        if (rs.next()) {
            return rs.getLong(1);
        }
        return -1;
    }

    // 根据ID查询订单
    public Order getOrderById(long orderId) throws Exception {
        String sql = "SELECT * FROM `order` WHERE order_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, orderId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    Order order = new Order();
                    order.setOrderId(rs.getLong("order_id"));
                    order.setUserId(rs.getLong("user_id"));
                    order.setOrderDate(rs.getTimestamp("order_date"));
                    order.setStatus(rs.getInt("status"));
                    order.setTotalAmount(rs.getDouble("total_amount"));
                    return order;
                }
            }
        }
        return null;
    }

    // 根据用户ID查询订单列表
    public List<Order> getOrdersByUserId(long userId) throws Exception {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM `order` WHERE user_id = ? ORDER BY order_date DESC";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Order order = new Order();
                    order.setOrderId(rs.getLong("order_id"));
                    order.setUserId(rs.getLong("user_id"));
//                    order.setProductId(rs.getLong("product_id"));
                    order.setOrderDate(rs.getTimestamp("order_date"));
                    order.setStatus(rs.getInt("status"));
                    order.setTotalAmount(rs.getDouble("total_amount"));
//                    order.setQuantity(rs.getInt("quantity"));
                    orders.add(order);
                }
            }
        }
        return orders;
    }

    // 更新订单状态
    public int updateOrderStatus(long orderId, int status) throws Exception {
        String sql = "UPDATE `order` SET status = ? WHERE order_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, status);
            pstmt.setLong(2, orderId);
            return pstmt.executeUpdate();
        }
    }

    // 更新订单所有字段
    public boolean updateOrder(Order order) throws SQLException {
        String sql = "UPDATE `order` SET user_id = ?, product_id = ?, order_date = ?, status = ?, total_amount = ?, quantity = ? WHERE order_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, order.getUserId());
//            pstmt.setLong(2, order.getProductId());
            pstmt.setTimestamp(3, order.getOrderDate());
            pstmt.setInt(4, order.getStatus());
            pstmt.setDouble(5, order.getTotalAmount());
//            pstmt.setInt(6, order.getQuantity());
            pstmt.setLong(7, order.getOrderId());
            return pstmt.executeUpdate() > 0;
        }
    }
}
